import { Component, toNative } from 'vue-facing-decorator'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { FilterDto } from '@/render/FilterRender'
import type { VxeColumnSlotTypes, VxeGridPropTypes, VxeTableDataRow } from 'vxe-table'
import type { AnyObject } from '@/types'
import {
    AllowStatusCnEnum,
    getKeyToEnum,
    InvoiceFromCnEnum,
    InvoiceTypeCnEnum,
    InvoiceUploadStatusCnEnum
} from '@/const/enum'
import DialogUpload from './components/DialogUpload'
import {
    exportInvoice,
    getInvoiceBatchList,
    getNeedSyncInvoiceList,
    uploadBatchInvoiceZip
} from '@/api/invoice'
import type { BatchInvoiceDto, InvoiceDto } from '@/api/invoice/types'
import { downloadFile } from '@/utils/util'
import {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import DialogHandleConflictInvoice from './components/DialogHandleConflictInvoice'
import PreviewImageOrPdf from '@/components/preview-media/PreviewImageOrPdf'
import dayjs from 'dayjs'
import { Button, message, RadioGroup, type UploadFile } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
import type { RadioGroupChildOption } from 'ant-design-vue/es/radio/Group'
@Component
export class BatchUpload extends TableRender {
    showUploadZip = false
    showUpload = false

    showInvoice = false

    uploadFile = null as File | null
    curItem = {} as InvoiceDto

    invoiceSyncList = [] as (InvoiceDto | BatchInvoiceDto)[]

    showDate = true

    invoiceFrom = InvoiceFromCnEnum.自开票

    filterConfig() {
        return {
            companyName: {
                name: '客户名称',
                element: 'autoComplete',
                class: 'w-full',
                placeholder: '请输入后选择',
                optionsType: 'company'
            },
            type: {
                name: '发票类型',
                element: 'select',
                options: getKeyToEnum(InvoiceTypeCnEnum, true)
            },
            isSync: {
                name: '是否同步',
                element: 'select',
                options: getKeyToEnum(AllowStatusCnEnum, true)
            },
            month: {
                name: '应用月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            }
        } as FilterDto
    }

    tableColumnConfigOld = () =>
        [
            {
                field: 'operate',
                title: '操作',
                fixed: 'left',
                width: 60,
                params: {
                    buttons: [
                        {
                            text: '处理',
                            event: (row: InvoiceDto) => {
                                this.onHandleInvoice(row)
                            }
                        }
                    ]
                },
                slots: {
                    default: 'buttons'
                }
            },
            {
                field: 'companyName',
                title: '客户名称',
                width: 200
            },
            {
                field: 'invoiceNo',
                title: '发票标识',
                width: 180
            },
            {
                field: 'invoiceName',
                title: '发票名称',
                width: 200
            },
            {
                field: 'updateTime',
                title: '上传时间',
                width: 160,
                formatter: ({ row }) => {
                    return row.updateTime
                        ? dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss')
                        : '--'
                }
            },
            {
                field: 'isSync',
                title: '是否同步',
                formatter: ({ row }) => {
                    return AllowStatusCnEnum[row.isSync]
                }
            },
            {
                field: 'type',
                title: '发票类型',
                formatter: ({ row }) => {
                    return InvoiceTypeCnEnum[row.type]
                }
            },
            {
                field: 'invoiceUrl',
                title: '发票',
                slots: {
                    default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
                        return (
                            <>
                                <PreviewImageOrPdf src={row.invoiceUrl} />
                            </>
                        )
                    }
                }
            },
            {
                field: 'openAmount',
                title: '原始发票金额',
                width: 120,
                slots: {
                    default: 'price'
                }
            },
            {
                field: 'syncAmount',
                title: '应用月份金额',
                width: 120,
                slots: {
                    default: 'price'
                }
            },
            {
                field: 'invoiceMonth',
                title: '应用月份'
            },
            {
                field: 'createTime',
                title: '创建时间',
                width: 160,
                formatter: ({ row }) => {
                    return row.updateTime
                        ? dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss')
                        : '--'
                }
            }
        ] as TableRenderColumnTypes<BatchInvoiceDto>

    basicFormConfig = this.initBasicFormConfig() as FormModalDto
    initBasicFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                invoiceFrom: {
                    name: '付款方式',
                    element: 'select',
                    defaultValue: 1,
                    required: true,
                    params: {
                        clearable: false
                    },
                    options: getKeyToEnum(InvoiceFromCnEnum)
                }
            },
            complete: async () => {},
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {
                initModelValue(this.basicFormConfig)
            }
        } as FormModalDto
    }

    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    onUploadZip() {
        this.showUploadZip = true
    }

    async onShowHandleInvoice() {
        this.invoiceSyncList = await this.getInvoiceList()
        this.showDate = true
        this.showInvoice = true
    }

    onHandleInvoice(row: InvoiceDto) {
        this.invoiceSyncList = [row]
        this.showDate = false
        this.showInvoice = true
    }

    async onExport() {
        const params = this.getFilters()
        params.status = InvoiceUploadStatusCnEnum.已上传
        const res = await exportInvoice(params)
        downloadFile(res)
    }

    async onConfirm(data: { file: UploadFile[]; close: () => void }, type: string) {
        if (!data.file?.length) {
            message.warning('请先上传文件')
            return
        }
        const fileData = new FormData()
        fileData.append('file', data.file[0]?.originFileObj as File)

        const params = getModelValue(this.basicFormConfig)

        fileData.append('invoiceFrom', params.invoiceFrom)

        await uploadBatchInvoiceZip(fileData)

        message.success('上传成功')
        this.reloadPage()
        data.close()
    }

    async getInvoiceList() {
        const res = await getNeedSyncInvoiceList({
            isSync: 0,
            month: ''
        })
        return res
    }

    onLoadData(page: number, size: number, filters: AnyObject) {
        filters.receiptIds = filters.receiptIds?.join(',') ?? ''
        return getInvoiceBatchList({
            pageNum: page,
            pageSize: size,
            ...filters
        })
    }

    async onMounted() {
        super.onMounted()
        this.basicForm = renderForm(this.basicFormConfig)
    }

    renderRightBtns() {
        return (
            <div class="flex gap-20px">
                <Button type="text" icon={h(UploadOutlined)} onClick={this.onUploadZip}>
                    上传
                </Button>
                <Button type="text" icon={h(UploadOutlined)} onClick={this.onShowHandleInvoice}>
                    批量处理
                </Button>
            </div>
        )
    }

    render() {
        return (
            <>
                {super.render()}
                <DialogUpload
                    v-model:show={this.showUploadZip}
                    onConfirm={(event) => this.onConfirm(event, 'zip')}
                    accept=".zip"
                    v-slots={{
                        header: () => {
                            return (
                                <div>
                                    <div class="text-lg font-bold mb-20px">上传发票：</div>
                                    <>{this.basicForm.element()}</>
                                </div>
                            )
                        },
                        filter: () => {
                            return <div class="flex items-center mb-10px">
                                <div class="mr-10px"><span class="text-error mr-4px">*</span>发票来源</div>
                                <RadioGroup v-model:value={this.invoiceFrom} options={getKeyToEnum(InvoiceFromCnEnum) as RadioGroupChildOption[]}>
                                </RadioGroup>
                            </div>
                        },
                        default: () => {
                            return (
                                <>
   
                                    <div class="text-sm text-black-200">
                                        {/* <div>
                                上传文件名称格式：电子签__年-月.zip；如：电子签__2022-01.zip
                                </div> */}
                                        <div>
                                        上传文件名称格式：日日保__年-月.zip；如：日日保__2022-01.zip
                                        </div>
                                    </div>
                                </>
                            )
                        }
                    }}
                />

                <DialogUpload
                    v-model:show={this.showUpload}
                    onConfirm={(event) => this.onConfirm(event, 'single')}
                />
                <DialogHandleConflictInvoice
                    v-model:show={this.showInvoice}
                    showDate={this.showDate}
                    invoicelist={this.invoiceSyncList}
                    onConfirm={this.reloadPage}
                />
            </>
        )
    }
}

export default toNative(BatchUpload)
